<template>
    {{pager}}{{myCurrentPage}}
  <div class="xtx-pagination">
    <a href="javascript:;" :class="{disabled : myCurrentPage===1}" @click="changePage(myCurrentPage-1)">上一页</a>
    <span>...</span>
    <a href="javascript:;" :class="{active : item===myCurrentPage}" @click="changePage(item)" v-for="item in pager.btnArr" :key="item">{{item}}</a>
    <span>...</span>
    <a href="javascript:;" :class="{disabled : myCurrentPage===pager.pageCount}" @click="changePage(myCurrentPage+1)">下一页</a>
  </div>
</template>
<script>
import { computed, ref, watch } from 'vue'
export default {
  name: 'XtxPagination',
  props: {
    total: {
      type: Number,
      default: 100
    },
    currentPage: {
      type: Number,
      default: 1
    },
    pageSize: {
      type: Number,
      default: 10
    }
  },
  setup (props, { emit }) {
    // 总条数
    const myTotal = ref(null)
    // 每页条数
    const myPageSize = ref(null)
    // 当前第几页
    const myCurrentPage = ref(null)
    watch(props, () => {
      myTotal.value = props.total
      myPageSize.value = props.pageSize
      myCurrentPage.value = props.currentPage
    }, { immediate: true })
    // 按钮个数
    const btnCount = 5
    const pager = computed(() => {
      // 计算总页数
      const pageCount = Math.ceil(myTotal.value / myPageSize.value)
      // 开始值
      let start = myCurrentPage.value - Math.floor(btnCount / 2) // 2
      // 结束值
      let end = start + btnCount - 1
      // 当当前页码过少时开始值会出现小于1
      if (start < 1) {
        start = 1
        end = (start + btnCount - 1) > pageCount ? pageCount : (start + btnCount - 1)
      }
      if (end > pageCount) {
        end = pageCount
        start = (end - btnCount + 1) < 1 ? 1 : (end - btnCount + 1)
      }
      const btnArr = []
      for (let i = start; i <= end; i++) {
        btnArr.push(i)
      }
      return { pageCount, start, end, btnArr }
    })
    const changePage = (val) => {
      if (val < 1 || val > pager.value.pageCount || myCurrentPage.value === val) {
        return
      }
      myCurrentPage.value = val
      emit('current-change', myCurrentPage.value)
    }
    return { pager, myCurrentPage, changePage }
  }
}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>
